<template>
  <div class="min-h-screen bg-gradient-to-br from-green-50 via-white to-blue-50">
    <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-12">
      <div class="text-center mb-12">
        <h1 class="text-4xl font-bold text-gray-900 mb-4">上传音频</h1>
        <p class="text-xl text-gray-600">上传音频文件，AI将自动转录并生成会议纪要</p>
      </div>

      <div class="max-w-4xl mx-auto">
        <!-- Upload Area -->
        <div
          class="card p-8 mb-8 border-2 border-dashed transition-colors duration-300"
          :class="{
            'border-primary-400 bg-primary-50': isDragging,
            'border-gray-300 bg-white': !isDragging
          }"
          @dragover.prevent="isDragging = true"
          @dragleave.prevent="isDragging = false"
          @drop.prevent="handleDrop"
        >
          <div class="text-center">
            <div class="w-20 h-20 bg-gradient-to-r from-green-500 to-emerald-600 rounded-2xl flex items-center justify-center mx-auto mb-6">
              <Upload class="w-10 h-10 text-white" />
            </div>

            <h3 class="text-xl font-semibold text-gray-900 mb-2">
              {{ selectedFile ? selectedFile.name : '拖拽音频文件到这里' }}
            </h3>

            <p class="text-gray-600 mb-6">
              支持格式：MP3, WAV, M4A, OGG, FLAC（最大100MB）
            </p>

            <div v-if="!selectedFile">
              <input
                ref="fileInput"
                type="file"
                accept="audio/*"
                @change="handleFileSelect"
                class="hidden"
              />
              <button
                @click="fileInput?.click()"
                class="btn-primary px-6 py-3 flex items-center gap-2 mx-auto"
              >
                <FolderOpen class="w-5 h-5" />
                选择文件
              </button>
            </div>

            <div v-else class="space-y-4">
              <!-- File Info -->
              <div class="bg-gray-50 rounded-lg p-4">
                <div class="flex items-center justify-between">
                  <div class="flex items-center gap-3">
                    <FileAudio class="w-8 h-8 text-green-600" />
                    <div>
                      <p class="font-medium text-gray-900">{{ selectedFile.name }}</p>
                      <p class="text-sm text-gray-600">
                        {{ formatFileSize(selectedFile.size) }} • {{ selectedFile.type }}
                      </p>
                    </div>
                  </div>
                  <button
                    @click="clearFile"
                    class="text-red-600 hover:text-red-700 p-2 hover:bg-red-50 rounded-lg transition-colors"
                  >
                    <X class="w-5 h-5" />
                  </button>
                </div>
              </div>

              <!-- Meeting Info -->
              <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div>
                  <label class="block text-sm font-medium text-gray-700 mb-2">
                    会议标题 *
                  </label>
                  <input
                    v-model="meetingInfo.title"
                    type="text"
                    class="input-field"
                    placeholder="输入会议标题..."
                  />
                </div>

                <div>
                  <label class="block text-sm font-medium text-gray-700 mb-2">
                    会议描述（可选）
                  </label>
                  <input
                    v-model="meetingInfo.description"
                    type="text"
                    class="input-field"
                    placeholder="输入会议描述..."
                  />
                </div>
              </div>

              <!-- One-click Processing Button -->
              <button
                @click="processAudioFile"
                :disabled="!meetingInfo.title || processing"
                class="btn-primary px-8 py-3 flex items-center gap-2 mx-auto"
              >
                <Loader2 v-if="processing" class="w-5 h-5 animate-spin" />
                <Zap v-else class="w-5 h-5" />
                {{ processing ? '处理中...' : '一键处理（转录+生成纪要）' }}
              </button>
            </div>
          </div>
        </div>

        <!-- Progress Modal -->
        <ProgressModal
          v-if="showProgressModal"
          :type="progressType"
          :title="progressTitle"
          :description="progressDescription"
          :progress="uploadProgress"
          :steps="progressSteps"
          :estimated-time="estimatedTime"
          @cancel="cancelProcessing"
        />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { useMeetingStore } from '@/stores/meeting'
import { useToastStore } from '@/stores/toast'
import { transcribeAudio, generateMinutes as generateMinutesApi } from '@/services/api'
import {
  Upload,
  FolderOpen,
  FileAudio,
  X,
  Zap,
  Loader2
} from 'lucide-vue-next'
import ProgressModal from '@/components/ui/ProgressModal.vue'

const router = useRouter()
const meetingStore = useMeetingStore()
const toastStore = useToastStore()

// Upload state
const isDragging = ref(false)
const selectedFile = ref<File | null>(null)
const fileInput = ref<HTMLInputElement>()
const processing = ref(false)
const uploadProgress = ref(0)

// Progress modal state
const showProgressModal = ref(false)
const progressType = ref<'uploading' | 'transcribing' | 'generating'>('uploading')
const progressTitle = ref('')
const progressDescription = ref('')
const progressSteps = ref([
  { name: '创建会议', completed: false },
  { name: '上传文件', completed: false },
  { name: 'AI转录', completed: false },
  { name: '生成纪要', completed: false },
  { name: '完成', completed: false }
])
const estimatedTime = ref('')

// Meeting info
const meetingInfo = reactive({
  title: '',
  description: ''
})

const currentMeetingId = ref<string>()

const handleDrop = (event: DragEvent) => {
  isDragging.value = false
  const files = event.dataTransfer?.files
  if (files && files.length > 0) {
    handleFile(files[0])
  }
}

const handleFileSelect = (event: Event) => {
  const input = event.target as HTMLInputElement
  if (input.files && input.files.length > 0) {
    handleFile(input.files[0])
  }
}

const handleFile = (file: File) => {
  // Check file type
  if (!file.type.startsWith('audio/')) {
    alert('请选择音频文件')
    return
  }

  // Check file size (100MB)
  if (file.size > 100 * 1024 * 1024) {
    alert('文件大小不能超过100MB')
    return
  }

  selectedFile.value = file
}

const clearFile = () => {
  selectedFile.value = null
  if (fileInput.value) {
    fileInput.value.value = ''
  }
}

const processAudioFile = async () => {
  if (!selectedFile.value || !meetingInfo.title) return

  try {
    processing.value = true

    // 初始化进度模态框 - 一键式处理
    showProgressModal.value = true
    progressType.value = 'uploading'
    progressTitle.value = 'AI智能音频处理'
    progressDescription.value = '正在为您处理音频文件，包含转录和生成会议纪要'
    progressSteps.value = [
      { name: '创建会议', completed: false },
      { name: '上传文件', completed: false },
      { name: 'AI转录', completed: false },
      { name: '生成纪要', completed: false },
      { name: '处理完成', completed: false }
    ]
    estimatedTime.value = '预计 3-6 分钟'

    // 步骤1: 创建会议
    uploadProgress.value = 5
    const meetingResponse = await meetingStore.createNewMeeting({
      title: meetingInfo.title,
      description: meetingInfo.description
    })
    const meeting = meetingResponse.meeting || meetingResponse
    currentMeetingId.value = meeting.id
    progressSteps.value[0].completed = true

    // 步骤2: 上传和转录音频
    progressType.value = 'transcribing'
    progressTitle.value = 'AI语音识别'
    progressDescription.value = '正在使用GPU加速转录音频内容'
    uploadProgress.value = 15

    await transcribeAudio(
      selectedFile.value,
      meeting.id,
      (progress) => {
        // 映射进度到整体进度：15% -> 60%
        const overallProgress = 15 + (progress * 0.45)
        uploadProgress.value = Math.floor(overallProgress)
        if (overallProgress >= 30) {
          progressSteps.value[1].completed = true
        }
        if (overallProgress >= 50) {
          progressSteps.value[2].completed = true
        }
      }
    )

    progressSteps.value[2].completed = true
    uploadProgress.value = 60

    // 步骤3: 生成会议纪要
    progressType.value = 'generating'
    progressTitle.value = 'AI智能生成纪要'
    progressDescription.value = '正在分析转录内容并生成结构化会议纪要'
    uploadProgress.value = 65

    await generateMinutesApi(
      meeting.id,
      '标准会议纪要',
      (progress) => {
        // 映射进度到整体进度：65% -> 95%
        const overallProgress = 65 + (progress * 0.30)
        uploadProgress.value = Math.floor(overallProgress)
        if (overallProgress >= 75) {
          progressSteps.value[3].completed = true
        }
        if (overallProgress >= 90) {
          progressSteps.value[4].completed = true
        }
      }
    )

    // 完成处理
    uploadProgress.value = 100
    progressSteps.value[4].completed = true

    // 短暂显示成功状态
    setTimeout(() => {
      showProgressModal.value = false
      // 跳转到历史记录页面
      router.push('/history')
    }, 2000)

    toastStore.success('音频处理完成！已在历史记录中查看结果')

  } catch (error) {
    console.error('Failed to process audio file:', error)
    toastStore.error('处理失败: ' + (error as Error).message)
    showProgressModal.value = false
  } finally {
    processing.value = false
  }
}

const cancelProcessing = () => {
  processing.value = false
  showProgressModal.value = false
  toastStore.warning('处理已取消')
}

const formatFileSize = (bytes: number) => {
  if (bytes === 0) return '0 Bytes'
  const k = 1024
  const sizes = ['Bytes', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}
</script>